import { AxiosRequestConfig } from "axios";
import { useState } from "react";
import { ApiConfigTypes } from "../config/api";
import apiHandler, {
  reqFulfilledPayload,
  reqIdlePayload,
  reqPendingPayload,
  reqRejectedPayload,
} from "../utils/apiHandler";

export function useRequest() {
  const [state, setState] = useState(reqIdlePayload);

  const fetchData = async (config: ApiConfigTypes | any, newData?: any) => {
    try {
      setState(reqPendingPayload);
      const { data } = await apiHandler({ ...config, data: newData });
      setState(reqFulfilledPayload(data));
    } catch (e) {
      setState(reqRejectedPayload(e));
    }
  };

  return {
    state,
    fetchData,
  };
}
